<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\GoodsCategory;

class GoodsCategoryController extends Controller
{
    /*
	 * 分类管理
	 * 
	 * */
	protected function index(){
		$cate = GoodsCategory::select('id','name','pid','sort')->orderBy('sort')->get();
		$list = array2level($cate);
		return view('admin.goodscategory.index',[
			'list'	=>$list
			]);
	}
	
	
	/*
	 * 分类添加
	 * */
	protected function add(Request $request){
		if($request->isMethod('post')){
			$input = $request->only('pid','name','image','sort');
			$cate = new GoodsCategory;
			$cate->name		= $input['name'];
			$cate->pid		= $input['pid'];
			$cate->image	= $input['image'];
			$cate->sort		= $input['sort'];
			if($cate->save()){
				return response()->json([
					'code'	=>'00000',
					'msg'	=>'分类添加成功!',
					'url'	=> route('admin.goodscategory.index')
					]);
			}else{
				return response()->json([
					'code'	=>'10001',
					'msg'	=>'分类添加失败!',
					'url'	=> ''
					]);				
			}

		}
		$pid = 0;
		if($request->has('pid')){
			$pid = $request->input('pid');
		}
		$cate = GoodsCategory::select('id','name','pid','sort')->get();
		$list = array2level($cate);		
		return view('admin.goodscategory.add',[
			'list'	=>$list,
			'pid'	=> $pid,
		]);
	}
	
	/*
	 * 
	 * 删除
	 * */
	protected function del($id){
		$cate = GoodsCategory::where('id',$id)->delete();
		if($cate){
			return response()->json([
				'code'	=>'00001',
				'msg'	=>'删除成功!',
				'url'	=> ''
				]);			
		}else{
			return response()->json([
				'code'	=>'10001',
				'msg'	=>'删除失败!',
				'url'	=> ''
				]);			
		}
	}
	
	
	/*
	 * 编辑
	 * 
	 * */
	protected function edit(Request $request){
		$id = $request->input('id');
		if($request->isMethod('post')){
			$input = $request->only('pid','name','image','sort');
			$cate = GoodsCategory::find($id);
			$cate->name		= $input['name'];
			$cate->pid		= $input['pid'];
			$cate->image	= $input['image'];
			$cate->sort		= $input['sort'];
			if($cate->save()){
				return response()->json([
					'code'	=>'00000',
					'msg'	=>'分类编辑成功!',
					'url'	=> route('admin.goodscategory.index')
					]);
			}else{
				return response()->json([
					'code'	=>'10001',
					'msg'	=>'分类编辑失败!',
					'url'	=> ''
					]);
			}
		}
		$cate_list = GoodsCategory::select('id','name','pid','sort')->get();
		$list = array2level($cate_list);
		$cate = GoodsCategory::find($id);
		return view('admin.goodscategory.edit',[
			'cate'	=> $cate,
			'list'	=>$list,
			]);
	}
}
